<template>
  <div class="tableRow">
    <el-row :gutter="10">
      <el-col :span="9">
        <el-card shadow="never" style="height: 120vh">
          <open-map mapWidth="100%" map-height="100vh" ref="areaMap" @positionChange="positionChangeHandler"
                    :vectorId="models.vectorId" :polygon="models.polygon" :position="models.position"></open-map>
        </el-card>
      </el-col>
      <el-col :span="9">
        <el-card shadow="never" style="height: 120vh">
          <div slot="header" class="ha-top">
              <n-title title="调查对象信息"/>
              <el-button size="small" plain type="primary" :loading="exportSurveyModelPDFLoading" @click="exportSurveyModelPDF">导出PDF</el-button>
          </div>
          <survey-model-manual ref="surveyComp" :operate-options="operateOptions" @invest-table-operate-click="handleOperateClick"
                               :structureId="models.structureId" tableHeight="80vh"></survey-model-manual>
          <div v-if="models.editTag == '1'" style="display: flex;align-items: center;justify-content: center">
            <el-button size="small" type="primary" @click="getBeforeData" >上一条</el-button>
            <el-button size="small" type="primary" :disabled="models.modifyTag != '1'" @click="confirmJudgeMark">确定</el-button>
            <el-button size="small" type="primary" :disabled="models.modifyTag != '1'">取消</el-button>
            <el-button size="small" type="primary" @click="getNextData">下一条</el-button>
          </div>
        </el-card>
      </el-col>
      <el-dialog title="指标错误原因" width="30%" custom-class="child-dialog"
                 :visible.sync="targetDialogVisible">
        <el-form :model="targetFormModel" :rules="rules" ref="targetFormRef">
          <el-form-item label="核查结果：" prop="markResult">
            <el-input v-model="targetFormModel.markResult" type="textarea" :autosize="{ minRows: 2, maxRows: 4}"
                      show-word-limit maxlength="200"></el-input>
          </el-form-item>
          <el-form-item label="原因分析：" prop="markReason">
            <el-input v-model="targetFormModel.markReason" type="textarea" :autosize="{ minRows: 2, maxRows: 4}"
                      show-word-limit maxlength="200"></el-input>
          </el-form-item>
          <el-form-item label="核查资料来源：" prop="markResource">
            <el-input v-model="targetFormModel.markResource" type="textarea" :autosize="{ minRows: 2, maxRows: 4}"
                      show-word-limit maxlength="200"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="targetDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveTargetErrorReason" :loading="targetLoading">确 定</el-button>
        </div>
      </el-dialog>
      <el-col :span="6">
        <el-card shadow="never" style="height: 120vh;font-size: 14px">
          <el-tabs v-model="activeTabName">
            <el-tab-pane label="核查判定" name="first">
              <div v-if="models.taskJudgeMarkList.length>0" >
                <el-row :gutter="10" v-for="(item, index) in models.taskJudgeMarkList" :key="index" style="margin-bottom: 5px">
                  <el-col :span="2">
                    <div class="resultDetailNumber">
                      {{index+1}}
                    </div>
                  </el-col>
                  <el-col :span="18">
                    <div style="padding-left: 10px">
                      （{{item.fieldName}}）核查结果：{{item.markResult}}，原因分析：{{item.markReason}}，核查资料来源：{{item.markResource}}
                    </div>
                  </el-col>
                  <el-col :span="4">
                    <el-button v-if="models.modifyTag=='1'" @click="deleteTargetErrorReason(item.id)" type="text" style="color: red" icon="el-icon-error"></el-button>
                  </el-col>
                </el-row>
              </div>
              <div v-else>暂无信息</div>
            </el-tab-pane>
            <el-tab-pane label="质检信息" name="second">
              <div v-if="models.inspectDetailList.length>0">
                <el-row :gutter="10" v-for="(item, index) in models.inspectDetailList" :key="index" style="margin-bottom: 5px">
                  <el-col :span="2">
                    <div class="resultDetailNumber">
                      {{index+1}}
                    </div>
                  </el-col>
                  <el-col :span="20">
                    <div style="padding-left: 10px">
                      <el-row :gutter="10">
                        <el-col :span="24">
                          <div class="resultDetailMsg">【{{item.subFieldName}}】{{item.resultMsg}}</div>
                        </el-col>
                      </el-row>
                      <el-row :gutter="10">
                        <el-col :span="24">
                          <el-input type="textarea" v-model="item.manualMsg" :disabled="true"/>
                        </el-col>
                      </el-row>
                    </div>
                  </el-col>
                </el-row>
              </div>
              <div v-else>暂无信息</div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script lang="ts">
import {Component, Ref, Vue} from 'vue-property-decorator';
import router from '@/router/index';
import OpenMap from '@/components/OpenMap.vue';
import SurveyModelManual from '@/components/verify/SurveyModelManual.vue';
import {getFormData} from '@/api/investDataCommon';
import NTab from "@/components/NTab.vue";
import NTitle from "@/components/NTitle.vue";
import QuickInput from "@/views/quality/components/QuickInput.vue";
import {queryResultDetailByDataId} from '@/api/inspectTask';
import {saveJudgeMark,
  selectJudgeMarkList,
  selectJudgeMarkTaskList,
  updateJudgeTaskState,
  deleteJudgeMark} from '@/api/verifyJudgeMark';
import {Message} from "element-ui";
import {downloadPdf} from '@/api/investStructure';

@Component({components: {QuickInput, NTitle, NTab, SurveyModelManual, OpenMap}})
export default class judgeMarkDetail extends Vue {
  @Ref("surveyComp") surveyComp!: any;
  @Ref("areaMap") areaMap!: any;
  @Ref('targetFormRef') private targetFormRef: any;
  exportSurveyModelPDFLoading : any = false;
  targetDialogVisible : any = false;
  targetLoading : any = false;
  activeTabName: any = 'first';
  dataRow:any = {};
  models: any = {
    taskId:router.currentRoute.query.taskId,
    structureId: router.currentRoute.query.structureId,
    dataId: router.currentRoute.query.dataId,
    editTag: router.currentRoute.query.editTag,
    modifyTag: router.currentRoute.query.editTag,
    verifyId: router.currentRoute.query.verifyId,
    workId: router.currentRoute.query.workId,
    vectorId: '',
    position: '',
    inspectResultId: '',
    dataIdList: [],
    inspectDetailList: [],
    taskJudgeMarkList : [],
    dataIndex:0
  }
  //指标错误原因表单
  targetFormModel:any = {
    judgeTaskId:router.currentRoute.query.taskId,
    fieldCode:'',
    fieldName:'',
    markResult:'',
    markReason:'',
    markResource:''
  };
  rules: any = {
    markResult: [
      {required: true, message: '请输入核查结果', trigger: 'blur'}
    ],
    markReason: [
      {required: true, message: '请输入原因分析', trigger: 'blur'}
    ],
    markResource: [
      {required: true, message: '请输入核查资料来源', trigger: 'blur'}
    ]
  };
  //模型操作列参数
  operateOptions:any = {
    operateColumnShow:true, //操作列是否展示
    operateTag:router.currentRoute.query.editTag == '1', //是否可操作
    operateLabel:'标记错误',  //操作按钮名称
    operateSuccessLabel: '已标记', //操作成功后显示名称
    disableCodeList:[] //不可操作列编码列表
  }

  //导出核查对象PDF
  exportSurveyModelPDF() {
    this.exportSurveyModelPDFLoading = true;
    downloadPdf({id:this.models.dataId, structureId: this.models.structureId, workId:this.models.workId}).then(res => {
      if (res && res.data) {
        (this as any).$download(res.data.fileName);
      }
    }).catch((e) => {
      console.error(e);
    }).finally(()=>{
      this.exportSurveyModelPDFLoading = false;
    })
  }

  //核查判定确认
  confirmJudgeMark() {
    updateJudgeTaskState({judgeTaskId:this.targetFormModel.judgeTaskId}).then(res=>{
      this.models.modifyTag = '0';
      this.operateOptions.operateTag = false;
      Message.success("确定成功");
    })
  }

  /**
   * 保存指标错误原因
   */
  saveTargetErrorReason() {
    this.targetLoading = true;
    this.targetFormRef.validate((valid) => {
      if (valid) {
        saveJudgeMark(this.targetFormModel).then(res=> {
          if (res.data) {
            Message.success("保存成功");
            this.targetLoading = false;
            this.queryTaskJudgeMarkList();
          } else {
            Message.error("保存失败")
          }
        }).catch(err=> {
          Message.error("保存失败")
        }).finally(()=>{
          this.targetDialogVisible = false
        })
      }
    });
  }
  //删除错误标记
  deleteTargetErrorReason(markId) {
    deleteJudgeMark({judgeMarkId:markId}).then(res=> {
      Message.success("删除成功");
      this.queryTaskJudgeMarkList();
    }).catch(err=> {
      Message.error("删除失败")
    })
  }
  //操作列触发事件
  handleOperateClick(row) {
    this.targetFormModel.fieldCode = row.inputCode;
    this.targetFormModel.fieldName = row.name;
    this.targetDialogVisible = true;
    this.dataRow = row
  }
  //地图
  positionChangeHandler(val) {
    if (val && val.length > 0) {
      this.models.formData.point = val.join(',');
    }
  }

  getBeforeData() {
    let currentIndex = this.models.dataIndex-1
    if (currentIndex<0) {
      return
    }
    this.models.dataIndex = currentIndex
    this.queryJudgeTaskList();
  }
  getNextData() {
    this.models.dataIndex = this.models.dataIndex + 1
    this.queryJudgeTaskList();
  }

  /**
   * 查询核查任务
   */
  queryJudgeTaskList() {
    let param = {
      pageNum:this.models.dataIndex,
      pageSize:1,
      judgeTaskId:this.models.taskId,
      verifyId:this.models.verifyId,
      workId:1,
      verifyTimes:1
    }
    selectJudgeMarkTaskList(param).then((res:any)=>{
      if(res.rows && res.rows.length>0) {
        let task = res.rows[0];
        this.models.dataId = task.dataCommonId;
        this.models.modifyTag = task.judgeState;
        this.targetFormModel.judgeTaskId = task.id;
        if(task.structureId != this.models.structureId) {
          this.models.structureId = task.structureId;
        }
        this.initData()
      }
    })
  }

  mounted() {
   this.initData();
  }
  //初始化数据
  initData() {
    this.getSurveyModelFormData();
    this.queryTaskJudgeMarkList();
    this.getResultDataDetailList();
  }

  /**
   * 查询调查表的数据
   */
  getSurveyModelFormData() {
    if (this.models.dataId) {
      getFormData({id: this.models.dataId}).then(res => {
        const common: any = res.data.commonForm;
        this.models.areaId = common.areaId;
        this.models.vectorId = common.vectorId;
        if (common.position) {
          this.models.position = common.position.split(',');
        }
        this.models.polygon = common.polygon;
        this.surveyComp.addFormData(res.data);
      })
    }
  }
  //查询任务错误标记原因列表
  queryTaskJudgeMarkList() {
    selectJudgeMarkList({judgeTaskId:this.targetFormModel.judgeTaskId}).then(res=> {
      if(res.data) {
        this.models.taskJudgeMarkList = res.data
        this.operateOptions.disableCodeList= res.data.map(item=>item.fieldCode);
      }
    })
  }
  /**
   * 查询质检结果、填报数据ID对应校验失败的数据
   */
  getResultDataDetailList() {
    if(this.models.dataId) {
      queryResultDetailByDataId({dataId: this.models.dataId}).then(res => {
        if (res.data) {
          this.models.inspectDetailList = res.data
        }
      })
    }
  }

  //重新加载数据用
  activated(){
    this.models.taskId=router.currentRoute.query.taskId;
    this.models.structureId=router.currentRoute.query.structureId;
    this.models.dataId=router.currentRoute.query.dataId;
    this.models.editTag=router.currentRoute.query.editTag;
    this.models.modifyTag=router.currentRoute.query.editTag;
    this.models.verifyId=router.currentRoute.query.verifyId;
    this.models.dataIndex=0;
    this.operateOptions.operateTag=router.currentRoute.query.editTag == '1';
    this.targetFormModel.judgeTaskId=router.currentRoute.query.taskId;
    this.initData()
  }
}
</script>
<style>
.ha-top {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .radio-t {
    display: flex;
    align-items: center;
    gap: 6px;

    span {
      font-size: 14px;
    }
  }
}
.inspectSpan {
  font-size: 15px;
  font-weight: bold;
  padding-bottom: 6px;
  cursor: pointer;
  width: fit-content;
  padding-left: 5px;
}
.resultDetailNumber{
  display: inline-block;
  background-color: #015751;
  padding: 5px 10px;
  font-size: 14px;
  color: white;
}
.resultDetailMsg{
  font-size: 15px;
  color: #015751;
}
.failMsgContent{
  font-size: 13px;
  font-weight: bold;
  padding-bottom: 6px;
  cursor: pointer;
  width: fit-content;
  padding-left: 20px;
}
</style>
